<?php

namespace app\v6\controller;

use think\Controller;
use think\Request;
use think\facade\Env;

class Upload extends Controller
{
    /**
     * 图片上传接口
     * @param Request $request
     * @return \think\response\Json
     */
    public function image(Request $request)
    {
        try {
            // 获取上传的文件
            $file = $request->file('file');
            
            if (empty($file)) {
                return json(['code' => 0, 'msg' => '请选择要上传的文件', 'data' => null]);
            }

            // 验证文件
            $validate = [
                'size' => 5242880, // 5MB
                'ext'  => 'jpg,jpeg,png,gif,webp,bmp'
            ];

            $info = $file->validate($validate)->move(Env::get('root_path') . 'public/uploads/images');
            
            if ($info) {
                // 生成访问URL
                $imageUrl = '/uploads/images/' . $info->getSaveName();
                
                // 返回成功响应
                return json([
                    'code' => 1,
                    'msg' => '上传成功',
                    'data' => [
                        'url' => $imageUrl,
                        'alt' => $info->getFilename(),
                        'href' => $imageUrl
                    ]
                ]);
            } else {
                return json(['code' => 0, 'msg' => $file->getError(), 'data' => null]);
            }
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '上传失败：' . $e->getMessage(), 'data' => null]);
        }
    }

    /**
     * 批量图片上传接口
     * @param Request $request
     * @return \think\response\Json
     */
    public function images(Request $request)
    {
        try {
            $files = $request->file('files');
            
            if (empty($files)) {
                return json(['code' => 0, 'msg' => '请选择要上传的文件', 'data' => null]);
            }

            $uploadedFiles = [];
            $errors = [];

            // 验证规则
            $validate = [
                'size' => 5242880, // 5MB
                'ext'  => 'jpg,jpeg,png,gif,webp,bmp'
            ];

            foreach ($files as $file) {
                $info = $file->validate($validate)->move(Env::get('root_path') . 'public/uploads/images');
                
                if ($info) {
                    $imageUrl = '/uploads/images/' . $info->getSaveName();
                    $uploadedFiles[] = [
                        'url' => $imageUrl,
                        'alt' => $info->getFilename(),
                        'href' => $imageUrl
                    ];
                } else {
                    $errors[] = $file->getError();
                }
            }

            if (!empty($uploadedFiles)) {
                return json([
                    'code' => 1,
                    'msg' => '上传完成',
                    'data' => $uploadedFiles,
                    'errors' => $errors
                ]);
            } else {
                return json(['code' => 0, 'msg' => '所有文件上传失败', 'data' => $errors]);
            }
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '上传失败：' . $e->getMessage(), 'data' => null]);
        }
    }

    /**
     * 删除图片接口
     * @param Request $request
     * @return \think\response\Json
     */
    public function deleteImage(Request $request)
    {
        try {
            $imageUrl = $request->post('url');
            
            if (empty($imageUrl)) {
                return json(['code' => 0, 'msg' => '图片URL不能为空', 'data' => null]);
            }

            // 构建文件路径
            $filePath = Env::get('root_path') . 'public' . $imageUrl;
            
            if (file_exists($filePath)) {
                if (unlink($filePath)) {
                    return json(['code' => 1, 'msg' => '删除成功', 'data' => null]);
                } else {
                    return json(['code' => 0, 'msg' => '删除失败', 'data' => null]);
                }
            } else {
                return json(['code' => 0, 'msg' => '文件不存在', 'data' => null]);
            }
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '删除失败：' . $e->getMessage(), 'data' => null]);
        }
    }

    /**
     * 获取图片信息
     * @param Request $request
     * @return \think\response\Json
     */
    public function getImageInfo(Request $request)
    {
        try {
            $imageUrl = $request->get('url');
            
            if (empty($imageUrl)) {
                return json(['code' => 0, 'msg' => '图片URL不能为空', 'data' => null]);
            }

            $filePath = Env::get('root_path') . 'public' . $imageUrl;
            
            if (file_exists($filePath)) {
                $imageInfo = getimagesize($filePath);
                $fileSize = filesize($filePath);
                
                return json([
                    'code' => 1,
                    'msg' => '获取成功',
                    'data' => [
                        'url' => $imageUrl,
                        'width' => $imageInfo[0] ?? 0,
                        'height' => $imageInfo[1] ?? 0,
                        'type' => $imageInfo['mime'] ?? '',
                        'size' => $fileSize,
                        'size_formatted' => $this->formatFileSize($fileSize)
                    ]
                ]);
            } else {
                return json(['code' => 0, 'msg' => '文件不存在', 'data' => null]);
            }
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '获取失败：' . $e->getMessage(), 'data' => null]);
        }
    }

    /**
     * 格式化文件大小
     * @param int $size
     * @return string
     */
    private function formatFileSize($size)
    {
        $units = ['B', 'KB', 'MB', 'GB'];
        $unitIndex = 0;
        
        while ($size >= 1024 && $unitIndex < count($units) - 1) {
            $size /= 1024;
            $unitIndex++;
        }
        
        return round($size, 2) . ' ' . $units[$unitIndex];
    }
}
